package com.seqb.common.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seqb.common.utils.RedisUtils;
import com.seqb.utils.DateUtils;
import com.seqb.utils.JsonUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @author lilinshen
 * @title 51Cto定时任务
 * @description 请填写相关描述
 * @date 2020/11/20
 */
public class Cto51Job implements Job {
    private static final Logger LOGGER = LoggerFactory.getLogger(Cto51Job.class);
    public static final HttpHeaders headers = new HttpHeaders();
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            Object taskParams = redisUtils.get("taskParams");
            List<String> requestUrlLists = new ArrayList<>();
            if (null != taskParams) {
                JSONArray parseArray = JSON.parseArray(taskParams.toString());
                for (int i = 0; i < parseArray.size(); i++) {
                    JSONObject item = parseArray.getJSONObject(i);
                    String type = item.getString("type");
                    if ("Cto51Job".equals(type)) {
                        JSONArray value = item.getJSONArray("value");
                        for (int j = 0; j < value.size(); j++) {
                            JSONObject jsonObject = value.getJSONObject(j);
                            headers.add(jsonObject.getString("key"), jsonObject.getString("value"));
                        }
                    }
                }
            }
            LOGGER.info("51Cto定时任务开始-----------" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            taskList();
            LOGGER.info("51Cto定时任务结束-----------" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean taskList() {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String requestUrl = "https://exam.51cto.com/ruankao.php/v1/index/exam-subject?id=1";
            HttpMethod httpMethod = HttpMethod.GET;
            Map<String, Object> paramsMap = new HashMap<>();
            HttpEntity httpEntity = new HttpEntity(JsonUtils.beanToJson(paramsMap), headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
            HttpStatus status = responseEntity.getStatusCode();
            if (status.equals(HttpStatus.OK)) {
                String entityBody = responseEntity.getBody();
                String code = JSON.parseObject(entityBody).getString("status");
                if (!"0".equals(code)) {
                    return false;
                }
                JSONArray data = JSON.parseObject(entityBody).getJSONArray("data");
                if (null == data || data.size() <= 0) {
                    return false;
                }
                for (int i = 0; i < data.size(); i++) {
                    JSONObject item = data.getJSONObject(i);
                    JSONArray son = item.getJSONArray("son");
                    if (null != son && son.size() > 0) {
                        for (int j = 0; j < son.size(); j++) {
                            JSONObject itemSon = son.getJSONObject(j);
                            String id = itemSon.getString("id");
                            String cname = itemSon.getString("cname");
                            practicePerday(id, cname);
                        }
                    }
                }
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 每天练习
     *
     * @param id   科目id
     * @param name 科目名称
     * @return
     */
    private boolean practicePerday(String id, String name) {
        try {
            LOGGER.info(name + "：每天练习开始", "yyyy-MM-dd HH:mm:ss");
            RestTemplate restTemplate = new RestTemplate();
            String requestUrl = "https://exam.51cto.com/ruankao.php/v1/practice/everyday";
            HttpMethod httpMethod = HttpMethod.GET;
            Map<String, Object> paramsMap = new HashMap<>();
            //切换科目
            headers.add("user-subject", id);
            HttpEntity httpEntity = new HttpEntity(JsonUtils.beanToJson(paramsMap), headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
            HttpStatus status = responseEntity.getStatusCode();
            if (status.equals(HttpStatus.OK)) {
                String entityBody = responseEntity.getBody();
                String code = JSON.parseObject(entityBody).getString("status");
                if (!"0".equals(code)) {
                    return false;
                }
                JSONArray data = JSON.parseObject(entityBody).getJSONObject("data").getJSONArray("data");
                if (null == data || data.size() <= 0) {
                    return false;
                }

                List<Map<String, Object>> answers = new ArrayList<>();
                for (int i = 0; i < data.size(); i++) {
                    JSONObject item = data.getJSONObject(i);
                    JSONObject answerItem = new JSONObject();
                    answerItem.put("qindex", i);
                    answerItem.put("done", "true");
                    answerItem.put("answer", item.getJSONArray("answer"));
                    answerItem.put("id", item.getString("question_id"));
                    answerItem.put("answer_type", item.getString("answer_type"));
                    answerItem.put("question_type", item.getString("question_type"));
                    answers.add(answerItem);
                }

                //睡眠10秒
                Thread.sleep(10000);

                //提交每天练习答案
                requestUrl = "https://exam.51cto.com/ruankao.php/v1/practice/every-submit";
                httpMethod = HttpMethod.POST;
                MultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<>();
                requestMap.add("date", "");
                requestMap.add("answer", JSONObject.toJSONString(answers));

                httpEntity = new HttpEntity(requestMap, headers);
                responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
                status = responseEntity.getStatusCode();
                if (status.equals(HttpStatus.OK)) {
                    entityBody = responseEntity.getBody();
                    JSONObject result = JSON.parseObject(entityBody);
                    code = result.getString("status");
                    if ("0".equals(code)) {
                        LOGGER.info(name + "：每天练习提交成功", "yyyy-MM-dd HH:mm:ss");
                    } else {
                        LOGGER.info(name + "：每天练习提交失败：" + entityBody);
                    }
                } else {
                    LOGGER.info(name + "：每天练习提交失败：" + entityBody);
                }
            }
            LOGGER.info(name + "：每天练习结束", "yyyy-MM-dd HH:mm:ss");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
